package net.sf.sqlparser.parser;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.FromItem;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.sqlparser.util.SQLParserUtils;

import org.apache.log4j.Logger;

/**
 * 测试据表查找Where部分.
 * @author lixiangyang
 *
 */
public class TestFindWhere {
	
	/**
	 * 日志.
	 */
	private static Logger log = Logger.getLogger(TestFindWhere.class);

	/**
	 * @param args
	 * @throws JSQLParserException 
	 */
	public static void main(String[] args) throws JSQLParserException {
		final String sql = "SELECT P.NAME AS A, P.CHN_NAME FROM RC_ENTITY E, RC_ENTITY_PROP P"
						+ " WHERE (E.ENTITY_ID = P.ENTITY_ID AND E.ENTITY_ID = '123')";
		parserSql(sql);
	}
	
	/**
	 * 解析SQL语句.
	 * @param sql SQL语句 .
	 * @throws JSQLParserException 解析异常.
	 */
	private static void parserSql(final String sql) throws JSQLParserException {
		// 1.解析SQL语句
		final SQLParserResult result = SQLParserUtils.parseWithTree(sql);
		final Statement stmt = result.getStmt();
		final SimpleNode rootNode = result.getStatementNode();
		
		// 2.据FromItem定位Where条件部分
		if (stmt instanceof Select) {
			final Select select = (Select) stmt;
			final PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
			final FromItem fromItem = plainSelect.getFromItem();
			final Expression whrExp = SQLParserUtils.findWhereByFromItem(fromItem, rootNode);
			if (whrExp != null) {
				log.debug("查找到的Where条件部分 = " + whrExp);
			} else {
				log.debug("没有找到Where条件部分");
			}
			
			// 测试追加Where条件
			final String appendWhereString = "1 = 1";
			final Expression resultWhrExp = SQLParserUtils.appendWhere(whrExp, appendWhereString);
			plainSelect.setWhere(resultWhrExp);
			log.debug("追加后的Where条件部分后的Select = " + plainSelect);
		}
	}
}
